package com.mikewoo.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * 
 * Title: SelectorSocketChannelDemo.java
 * Description:  SelectorSocketChannel客户端
 * 
 * author     Phantom
 * date       2016年5月20日 上午10:16:41
 * @version    1.0.0
 */
public class SelectorSocketChannelDemo {
	
	public static void startClient() throws Exception {
		SocketChannel socketChannel = SocketChannel.open(); // 打开Channel
		socketChannel.connect(new InetSocketAddress("localhost", 8999)); // 连接服务端
		
		socketChannel.configureBlocking(false); // 设置连接属性
		
		Selector selector = Selector.open(); // 打开Selector
		socketChannel.register(selector, SelectionKey.OP_READ); // 注册socketChannel到selector
		
		ByteBuffer byteBuffer = ByteBuffer.wrap("hello 客户端".getBytes("UTF-8"));
		socketChannel.write(byteBuffer);
		byteBuffer.clear();
		
		new ClientThread(selector).start(); // 开启新线程轮询处理服务端发过来的数据
	} 
	
	public static void main(String[] args) throws Exception {
		startClient();
	}
}
